package com.xph.core.common.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.apache.wink.client.ClientConfig;
import org.apache.wink.client.ClientResponse;
import org.apache.wink.client.Resource;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;






/**
 * REST工具
 * @author Administrator
 *
 */
public class RestUtil {
	
	private static Logger log = Logger.getLogger(RestUtil.class);
	
	public static String REST_URL = "http://localhost:80/rm/rest";
	//结果相关常量
	public static final String RESULT_CODE = "code";
	public static final String RESULT_MESSAGE = "message";
	public static final String RESULT_TOTAL = "total";
	public static final String RESULT_SUCCESS = "0000";//成功
	public static final String RESULT_FAILURE = "9999";//失败
	
	private static final String DEFAUT_CONTENTTYPE = "application/json";
    private static Pattern pattern = Pattern.compile("http://([\\d\\w\\.]+)(:(\\d+))?/\\S+");
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    private static Calendar c = Calendar.getInstance();

	
    private static final HashMap sourceMap = new HashMap();
    static{
    }
    
    public static JSONObject restGet(String url) { //REST接口get请求   	
    	if(log.isDebugEnabled()){
    		log.debug("rest request:" + url); 
    	}
    	url = transUrl(url);
    	ClientConfig config=new ClientConfig();
    	String[] proxy = getProxyParams(url);
    	config.proxyHost(proxy[0]);
    	config.proxyPort(Integer.parseInt(proxy[1]));
    	org.apache.wink.client.RestClient restclient=new org.apache.wink.client.RestClient(config);
        Resource resource = restclient.resource(url);
        ClientResponse response = resource.contentType(DEFAUT_CONTENTTYPE).get();
        JSONObject jsonObj = response.getEntity(JSONObject.class);
        if(log.isDebugEnabled()){
        	log.debug("rest response:" + jsonObj.toString());
        }
        return jsonObj;
    }
    
    private static String[] getProxyParams(String hosturl){
    	Matcher matcher = pattern.matcher(hosturl);
    	String[] proxy=new String[2];
    	if(matcher.find()){
    		proxy[0]=matcher.group(1);
    		if(matcher.group(3) == null){
        		proxy[1]="80";
    		}else{
        		proxy[1]=matcher.group(3);
    		}
    	}else{
    		proxy[0]="127.0.0.1";
    		proxy[1]="6000";
    		log.error("get rest service proxy error: "+hosturl);
    	}
    	return proxy;
    }
    
    public static JSONObject restPost(String url, JSONObject jsonParas) { //REST接口post请求
    	if(log.isDebugEnabled()){
    		log.debug("rest request:" + url +", jsonParas:"+(jsonParas==null?null:jsonParas.toString())); 
    	}
    	org.apache.wink.client.RestClient restclient=new org.apache.wink.client.RestClient();
    	Resource resource = restclient.resource(url);
        ClientResponse response = resource.contentType(DEFAUT_CONTENTTYPE).accept(DEFAUT_CONTENTTYPE).post(jsonParas);
        JSONObject jsonObj = response.getEntity(JSONObject.class);
        if(log.isDebugEnabled()){
        	log.debug("rest response:" + jsonObj.toString());
        }
        return jsonObj;
    }
    
    public static JSONObject getSuccessResult(Object msg) {
        JSONObject obj = new JSONObject();
        try {   
            obj.put(RestUtil.RESULT_CODE, RestUtil.RESULT_SUCCESS);
            obj.put(RestUtil.RESULT_MESSAGE, msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }
    
    public static JSONObject getFailureResult(Object msg) {
        JSONObject obj = new JSONObject();
        try {   
            obj.put(RestUtil.RESULT_CODE, RestUtil.RESULT_FAILURE);
            obj.put(RestUtil.RESULT_MESSAGE, msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }  
    
    public static JSONObject getErrorResult(Object msg,String errorcode) {
        JSONObject obj = new JSONObject();
        try {   
            obj.put(RestUtil.RESULT_CODE, errorcode);
            obj.put(RestUtil.RESULT_MESSAGE, msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }  
	
	public static String transUrl(String url){
	    url = url.replaceAll("\\|", "%7C");
	    url = url.replaceAll("\\!", "%21");
	    url = url.replaceAll("\\#", "%23");
	    url = url.replaceAll("\\$", "%24");
	    url = url.replaceAll("\\%", "%25");
	    url = url.replaceAll("\\^", "%5E");
	    return url;
	}
	
	public static String transUrl2(String url){
        url = url.replaceAll("%7C","\\|");
        url = url.replaceAll("%21","\\!");
        url = url.replaceAll("%23","\\#");
        url = url.replaceAll("%24","\\$");
        url = url.replaceAll("%25","\\%");
        url = url.replaceAll("%5E","\\^");
        return url;
    }
	
}
